<!-- 文书树 -->
<template>
  <el-card shadow="never">
    <!-- <el-input v-model="deptName" placeholder="文书类别" clearable>
      <template #prefix>
        <i-ep-search />
      </template>
    </el-input> -->
    <text>文书分类</text>
    <el-tree
      ref="deptTreeRef"
      class="mt-2"
      :data="deptList"
      :props="{ children: 'children', label: 'category', disabled: '' }"
      :expand-on-click-node="false"
      :filter-node-method="handleFilter"
      default-expand-all
      @node-click="handleNodeClick"
    />
  </el-card>
</template>

<script setup lang="ts">
import inscategoryAPI from "@/api/inscategory";
import instypeAPI from "@/api/instype";
const props = defineProps({
  modelValue: {
    type: [Number],
    default: undefined,
  },
});

const deptList = ref<any>([]); // 文书列表
const deptTreeRef = ref(ElTree); // 文书树
const deptName = ref(); // 文书名称

const emits = defineEmits(["node-click"]);

const deptId = useVModel(props, "modelValue", emits);

watchEffect(
  () => {
    deptTreeRef.value.filter(deptName.value);
  },
  {
    flush: "post", // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 文书筛选 */
function handleFilter(value: string, data: any) {
  if (!value) {
    return true;
  }
  return data.label.indexOf(value) !== -1;
}

/** 文书树节点 Click */
function handleNodeClick(data: { [key: string]: any }) {
  console.log(data, "文书筛选");
  if (data.children) {
    return false;
  }
  deptId.value = data.id;
  emits("node-click");
}

onBeforeMount(async () => {
  await inscategoryAPI.getInsCategory().then((data) => {
    deptList.value = data.map((item) => ({
      ...item,
      children: [],
    }));
  });
  await instypeAPI.getInstype().then((data) => {
    data.forEach((newItem) => {
      let matchingItem = deptList.value.find(
        (item: any) => item.category === newItem.categoryName
      );
      if (matchingItem) {
        matchingItem.children.push({
          id: newItem.id,
          category: newItem.typeName,
        });
      }
    });
  });
  deptId.value = deptList.value[0].children[0].id;
  emits("node-click");
});
</script>
